<template>
  <div class="upload-json">
    <a-upload :file-list="fileList" name="file" :before-upload="beforeUpload">
      <div class="upload-btn">
        选择文件
      </div>
    </a-upload>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';
import * as FileApi from '@/api/download';
import { message } from 'ant-design-vue';

const fileList = ref<any>([]);
const uploading = ref(false);
const beforeUpload = file => {
  if (file.type === 'application/json') {
    fileList.value = [file];
  } else {
    message.error('只能上传JSON文件!')
  }
  return false;
};
const handleUpload = async () => {
  const formData = new FormData();
  const file = fileList.value[0];
  formData.append('file', file);
  uploading.value = true;
  const res = await FileApi.uploadJSON(formData);
  if (res) {
    uploading.value = false;
    message.success('上传成功');
  } else {
    uploading.value = false;
    message.error('上传失败');
  }
};
watch(() => fileList.value, () => {
  if (fileList.value.length) {
    handleUpload();
  }
})
</script>

<style lang="scss" scoped>
.upload-json {
  padding-top: 12px;

  .upload-btn {
    background: rgba(2, 54, 73, 0.55);
    border: 1px solid rgba(0, 117, 129, 1);
    line-height: 30px;
    color: #999999;
    padding: 0 11px;
    border-radius: 5px;
    cursor: pointer;
  }
}
</style>
